;(function($){
	var _selectChange = function(ref, refUrl, postField, selectValue, $page) {
		if (!selectValue || !refUrl) {
			return;
		}
		var refData;
		if (refUrl) {
			var postData = {};
			postData[postField] = selectValue;
			$.DWZajax({
				url: refUrl,
				type: 'POST',
				dataType : "json",
				data: postData,
				async: false,
				cache: false,
				callback: function(data) {
					refData = data
				}
			});
		}
		var allys = ref.split(";");
		
		$.each(allys, function() {
			// 获取级联的select
			var $allySelect = $('#' + this, $page).empty(),
			field = $allySelect.attr('field') || $allySelect.attr('name'),
			label = $allySelect.attr('label') || $allySelect.attr('text'),
			mapKey = $allySelect.attr('mapKey') || field + 's',
			value = $allySelect.attr('selectedValue'),
			data = [];
			
			if (allys.length == 1 && refData) {
				data = refData;
			} else if (refData && refData[mapKey]) {
				data = refData[mapKey];
			}
			$.each(data, function() {
				var $option = $('<option/>').attr('value', this[field]).text(this[label]);
				if (this[field] == value) {
					$option.attr('selected', true);
					$allySelect.removeAttr('selectedValue');
				}
				$allySelect.append($option);
			});
		});
	};
	$.fn.extend({
		selectally: function () {
			return this.each(function(){
				var $select = $(this), 
				ref = $select.attr('ref'), 
				refUrl = $select.attr('refUrl'), 
				postField = $select.attr('postField') || $select.attr('name'),
				//修改bug，查找范围太局限，不能指定就在pageContent里面
				$page = DWZ.context() || $(document);
				$select.on('change', function(){
					_selectChange(ref, refUrl, postField, this.value, $page);
					$select.trigger('select');
				});
				$select.change();
			});
		}
	});
})(jQuery);